import cookies from './util.cookies'
import db from './util.db'
import log from './util.log'
import { userMenu } from '@/api/system/user'
import storage from '@/libs/util.Localstorage'
import dateTools from '@/libs/util.date'
// eslint-disable-next-line no-unused-vars
import { Message } from 'element-ui'
import store from '@/store'

const util = {
  cookies,
  db,
  log,
  storage,
  dateTools
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE || 'D2Admin'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'd2admin-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-link-temp'))
}

util.userMenu = function (callback) {
  userMenu().then(e => {
    callback(e)
  })
}

// util.tree = function (list, pid, cld) {
//   const res = []
//   const hash = new Map()
//   // 将数组转为Object的形式，key为数组中的id
//   for (const item of list) {
//     hash.set(item.id, item)
//   }
//   for (const eve of list) {
//     const parent = hash.get(eve[pid])
//     if (parent) {
//       if (parent[cld]) {
//         parent[cld].push(eve)
//       } else {
//         parent[cld] = []
//         parent[cld].push(eve)
//       }
//     } else {
//       res.push(eve)
//     }
//   }
//   return res
// }

util.treeMenu = function (list, pid, cld) {
  const res = []
  const hash = new Map()
  const data = []
  for (const t of list) {
    data.push({
      id: t.id,
      pid: t[pid],
      path: util.isBlank(t.router) ? `${t.path}` : `/${t.router}`,
      name: t.path,
      component: t.router,
      title: t.name,
      icon: t.icon
    })
  }
  // 将数组转为Object的形式，key为数组中的id
  for (const item of data) {
    hash.set(item.id, item)
  }
  for (const eve of data) {
    const parent = hash.get(eve[pid])
    if (parent) {
      if (parent[cld]) {
        parent[cld].push(eve)
      } else {
        parent[cld] = []
        parent[cld].push(eve)
      }
    } else {
      res.push(eve)
    }
  }
  return res
}

util.tree = function (list, pid, cld, id) {
  const res = []
  const hash = new Map()
  for (const item of list) {
    hash.set((id && item[id]) || item.id, item)
  }
  for (const eve of list) {
    const parent = hash.get(eve[pid])
    if (parent) {
      if (parent[cld]) {
        parent[cld].push(eve)
      } else {
        parent[cld] = []
        parent[cld].push(eve)
      }
    } else {
      res.push(eve)
    }
  }
  return res
}

util.eq = function (a, b) {
  if (a === undefined || b === undefined) {
    return false
  }
  return a + '' === b + ''
}
// 为空
util.isBlank = function (value) {
  return (value === undefined || value === null || value === '' || value === 'null' || value === 'undefined')
}
// 非空
util.isNotBlank = function (value) {
  return (value !== undefined && value !== null && value !== '' && value !== 'null' && value !== 'undefined')
}
// 非空
util.isNotBlanks = function (...value) {
  if (value === undefined) {
    return false
  }
  for (const item of value) {
    if (item === undefined || item === '' || item === 'null' || item === 'undefined') {
      return false
    }
  }
  return true
}
// 验证对象里的值
util.checkMapNotNull = function (obj, ...key) {
  if (obj === undefined) {
    return false
  }
  for (const item of key) {
    if (obj[item] === undefined || util.isBlank(obj[item])) {
      return false
    }
  }
  return true
}
util.success = function (t, msg) {
  t.$message({
    message: msg,
    type: 'success',
    duration: 3 * 1000
  })
}
util.warning = function (t, msg) {
  t.$message({
    message: msg,
    type: 'warning',
    duration: 5 * 1000
  })
}
util.error = function (t, msg) {
  t.$message({
    message: msg,
    type: 'error',
    duration: 5 * 1000
  })
}

util.msg_info = function (t, msg) {
  t.$message({
    message: msg,
    type: 'info',
    duration: 5 * 1000
  })
}

util.user = function () {
  return store.getters['d2admin/user/getUserInfo']
}

util.isSuper = function () {
  const user = store.getters['d2admin/user/getUserInfo']
  return (user && user.superMan) || false
}
// 公用提交表单请求
util.request = function (THIS, FUNCTION, PARAM, REFRESH, MSG, CALLBACK) {
  FUNCTION(PARAM).then(res => {
    THIS.loading = false
    res && util.success(THIS, MSG || '操作成功')
    res && THIS.closeModal && THIS.closeModal()
    res && REFRESH && REFRESH()
    res && CALLBACK && CALLBACK(res)
  }).catch(e => {
    THIS.loading = false
    console.error('操作失败：', e)
  })
}
// 查询并赋值
util.query = function (T, FUNCTION, PARAM, STATE) {
  FUNCTION(PARAM || '').then(res => {
    T[STATE] = res && res
  }).catch(e => {
    console.error('查询失败：', e)
  })
}
// 查询
util.queryVal = function (T, FUNCTION, PARAM, MSG, CATCH_FUNC, CALLBACK) {
  FUNCTION(PARAM || '').then(res => {
    CALLBACK && CALLBACK(res)
  }).catch(e => {
    console.error('查询失败：', e)
    // MSG && util.warning(T, MSG)
    CATCH_FUNC && CATCH_FUNC()
    throw new Error(e)
  })
}
// 删除公用弹出
util.openDel = function (T, param, title, del, refresh) {
  T.$confirm(`此操作将永久删除 ${title}, 是否继续 ?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    del && util.request(T, del, param, refresh, '删除成功')
    // refresh && refresh()
  }).catch(() => {
    util.msg_info(T, '已取消删除')
  })
}
// 公用禁用
util.openEnable = function (T, param, title, enable, refresh, msg) {
  T.$confirm(`此操作将 ${title}, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    enable && util.request(T, enable, param, refresh, msg)
  }).catch(() => {
    util.msg_info(T, '已取消操作')
  })
}
// 公用弹窗确认
util.messageBox = function (T, msg, title, type, func, param, refresh) {
  T.$confirm(msg, title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: type
  }).then(() => {
    func(param).then(res => {
      res && util.success(T, '操作成功')
      res && refresh && refresh()
    })
  }).catch((e) => {
    console.log('e:', e)
    util.msg_info(T, '已取消操作')
  })
}
util.replace = function (str, th, msg) {
  return str.replaceAll(th, msg)
}
util.replaceAll = function (str, msg, ...th) {
  th.forEach(e => {
    str = util.replace(str, e, msg)
  })
  return str
}

// 车辆产地国别
util.counties = function () {
  return ['中国', '德国', '日本', '美国', '韩国', '法国', '英国', '意大利', '瑞典', '荷兰', '捷克', '其他']
}

export default util
